import React, { useRef, useState, useEffect } from 'react'
import { PageContainer } from '@ant-design/pro-layout'
import { PlusOutlined, UserOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { Button, Avatar, Switch, message, Image, Modal,Input } from 'antd';
import ProTable from '@ant-design/pro-table';
import { getSlides, lockSlides, deleteSlides,sortSlides } from '@/services/slides'
import { set } from 'lodash';
import CreateOrEdit from './components/CreateOrEdit';

const User = () => {
  const { confirm } = Modal;
  //表格的ref，便于自定义操作表格
  const actionRef = useRef()
  //将表单初始化的值设置为状态，在编辑的时候，使用这个状态
  const [isModalVisible, setIsModalVisible] = useState(false)
  const [editId, setEditId] = useState(undefined)
  
  const handleBlur=async (id,e)=>{
    let value=parseInt(e.target.value)
    let data={seq:value}
    const res=await sortSlides(id,data)
    console.log(res);
    if (res.status === undefined) {
      message.success(`排序更新成功`)
      //刷新表格数据
      actionRef.current.reload()
    }
  }
  //删除模态框的显示
  function showConfirm(id) {
    confirm({
      icon: <ExclamationCircleOutlined />,
      content: '确定要删除该轮播图吗？',
      async onOk() {
        const res=await deleteSlides(id)
        console.log(res);
        if (res.status === undefined) {
          message.success(`删除成功`)
          //刷新表格数据
          actionRef.current.reload()
        }
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }
  //是否禁用用户
  const lockSlidesFun = async (editId) => {
    const res = await lockSlides(editId)
    if (res.status === undefined) {
      message.success('操作成功')
    } else {
      message.error('操作失败')
    }
  }
  //控制模态框显示和隐藏
  const isShowModal = (show, id = undefined) => {
    setEditId(id)
    setIsModalVisible(show)
  }

  const columns = [
    {
      title: '轮播图片',
      dataIndex: 'img_url',
      hideInSearch: true,
      render: (_, record) => <Image width={64} src={record.img_url} />
    }, {
      title: '标题',
      // hideInSearch: true,
      dataIndex: 'title'
    }, {
      title: '跳转连接',
      dataIndex: 'url',
      hideInSearch: true,
    }, {
      title: '是否禁用',
      dataIndex: 'status',
      hideInSearch: true,
      render: (_, record) => <Switch checkedChildren="启用" unCheckedChildren="禁用"
        defaultChecked={record.status === 0} onChange={() => lockSlidesFun(record.id)} />
    }, {
      title: '排序',
      dataIndex: 'seq',
      hideInSearch: true,
      render:(_,record)=><Input type="number" placeholder="请输入排序序号" defaultValue={record.seq} bordered={false} onBlur={(e)=>handleBlur(record.id,e)} name="seq"/>
    }, {
      title: '修改时间',
      dataIndex: 'updated_at',
      hideInSearch: true
    }, {
      title: '操作',
      render: (_, record) => {
        return (
          <div>
            <a onClick={() => isShowModal(true, record.id)}>编辑&nbsp;</a>
            <a onClick={() => showConfirm(record.id)}>&nbsp;删除</a>
          </div>)
      },
      hideInSearch: true
    }
  ]
  //获取用户列表
  const getData = async (params) => {
    const res = await getSlides(params)
    return {
      data: res.data,
      success: true,
      total: res.meta.pagination.total
    }
  }
  return (
    <PageContainer>
      <ProTable
        columns={columns}
        actionRef={actionRef}
        request={async (params = {}) => getData(params)}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        pagination={{
          pageSize: 10,
        }}
        dateFormatter="string"
        headerTitle="轮播图列表"
        toolBarRender={() => [
          <Button key="button" icon={<PlusOutlined />} type="primary"
            onClick={() => isShowModal(true)} >
            新建
          </Button>,
        ]}
      />
      {
        //模态框隐藏的时候，不挂载组件，模态框显示时候再挂载组件，这样是为了触发子组件的生命周期
        !isModalVisible ? '' :
          <CreateOrEdit isModalVisible={isModalVisible}
            isShowModal={isShowModal} actionRef={actionRef} editId={editId} />
      }

    </PageContainer>
  )
}

export default User
